import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { Button, Table, Modal, Space, Form, Input, message as antdMessage, Select, Image } from 'antd'
import { useForm } from 'antd/es/form/Form'
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom'
const { Option } = Select

interface ListRawState {
  "id": string,
  "image": string,
  "nickname": string,
  "price": number,
  "title": string,
  "state|1": string,
  "tel": string,
  "address": string
}

const Index: React.FC = () => {
  const { search } = useLocation()
  // 1. 容器
  const [list, setList] = useState<ListRawState[]>([])
  // 2. 请求函数
  const fetchList = async () => {
    const resp = await axios.get('/api/order?q=' + q);
    setList(resp.data.data)
  }
  // 3. 副作用函数
  useEffect(() => {
    fetchList()
  }, [search])
  // 5. 定义 删除函数
  const handleDelete = (id: string) => {
    Modal.confirm({
      title: '警告',
      content: '确认要删除该项数据吗？',
      onOk() {
        axios.delete(`/api/order/${id}`).then(() => {
          fetchList();
        })
      }
    })

  }
  // 6. 定义 临时选中id的列表
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  // 4. 定义 columns 列表项目
  const columns = [
    {
      key: 1,
      title: <div>
        <Button onClick={() => handleSelectedDelete()} type="primary" danger disabled={selectedRowKeys.length === 0}>删除所选</Button>
      </div>,
      dataIndex: 'id'
    },
    {
      key: 2,
      title: '标题',
      dataIndex: 'title'
    },
    {
      key: 3,
      title: '昵称',
      dataIndex: 'nickname'
    },
    {
      key: 41231231,
      title: '图片',
      dataIndex: 'image',
      render(image: string) {
        return <Image src={image} alt="" width={30} height={30}/>
      }
    },
    {
      key: 5,
      title: '状态',
      dataIndex: 'state'
    },
    {
      key: 6,
      title: '地址',
      dataIndex: 'address'
    },
    {
      key: 7,
      title: '电话',
      dataIndex: 'tel'
    },
    {
      key: 8,
      title: '总价',
      dataIndex: 'price'
    },
    {
      key: 9,
      title: '操作',
      dataIndex: 'id',
      render(id: string, rawData: ListRawState) {
        return (
          <Space>
            <Button type="primary" onClick={() => openDialog(rawData)}>编辑</Button>
            <Button onClick={() => handleDelete(id)} type="primary" danger>删除</Button>
          </Space>
        )
      }
    }
  ]
  // 7. 删除选中的数据函数
  const handleSelectedDelete = () => {
    // 方案一：
    // const requests = selectedRowKeys.map(id => {
    //   return axios.delete('/api/order/' + id)
    // })
    // Promise.all(requests).then(() => {
    //   fetchList()
    // })
    // 方案二：
    Modal.confirm({
      title: '警告',
      content: '确认要删除所选数据吗？',
      onOk() {
        axios.delete('/api/order/' + selectedRowKeys.join(',')).then(() => {
          fetchList()
        })
      }
    })
  }
  // 8. 定义打开弹框的函数
  const openDialog = (rawData: ListRawState) => {
    setIsOpen(true);
    form.setFieldsValue(rawData)
  }
  // 9. 定义弹框的状态
  const [isOpen, setIsOpen] = useState(false)
  // 10. 定义 form 实例
  const [form] = useForm();
  // 11. 定义 确定修改函数
  const handleOK = () => {
    // 获取 form 表单内容
    const data: ListRawState = form.getFieldsValue()
    // 发送请求
    axios.post(`/api/order/${data.id}`, data).then((resp) => {
      const { code, message } = resp.data;
      if(code === 200) {
        fetchList()
        antdMessage.success(message)
      } else {
        antdMessage.error(message)
      }
    }).finally(() => {
      setIsOpen(false)
    })
  }
  // 12. 
  const [searchParams] = useSearchParams();
  const q = searchParams.get('q') || ""
  // 13. 会车
  const onSearch = (q: string) => {
    if(q) {
      navigate('/list?q=' + q)
    }
  }
  //14. 获取 hooks
  const navigate = useNavigate()
  return (
    <div>
      {/* 筛选 */}
      <Input.Search defaultValue={q} onSearch={onSearch}></Input.Search>
      {/* 表格 */}
      <Table
        rowSelection={{
          onChange(selectedRowKeys: React.Key[]) {
            console.log('选中项目改变了!', selectedRowKeys);
            setSelectedRowKeys(selectedRowKeys)
          }
        }}
        rowKey={'id'}
        dataSource={list}
        columns={columns}
        pagination={{ pageSize: 5 }}
      ></Table>
      {/* 弹框 */}
      <Modal
        onOk={() => handleOK()}
        onCancel={() => setIsOpen(false)}
        open={isOpen}
        title="编辑"
        okText="确认"
        cancelText="取消"
      >
        <Form form={form} wrapperCol={{ span: 20 }} labelCol={{ span: 4 }}>
          <Form.Item label="id" name="id">
            <Input disabled></Input>
          </Form.Item>
          <Form.Item label="title" name="title">
            <Input></Input>
          </Form.Item>
          <Form.Item label="image" name="image">
            <Input></Input>
          </Form.Item>
          <Form.Item label="state" name="state">
            <Select>
              {
                ["待付款", "待发货", "待收货", "待评价", "已完成"].map((v, i) => {
                  return <Option key={i} value={v}>{v}</Option>
                })
              }
            </Select>
          </Form.Item>
          <Form.Item label="address" name="address">
            <Input></Input>
          </Form.Item>
          <Form.Item label="tel" name="tel">
            <Input></Input>
          </Form.Item>
          <Form.Item label="nickname" name="nickname">
            <Input></Input>
          </Form.Item>
          <Form.Item label="price" name="price">
            <Input></Input>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default Index